<template>
  <div class="box">
    <div class="top">
      <h1>商品列表</h1>
    </div>
    <div class="content">
      <el-table :data="tableData" :border="parentBorder" :preserve-expanded-content="preserveExpanded" border
        style="width: 100%" height="450">
        <el-table-column type="expand">
          <template #default="props">
            <div m="4" class="launched">
              <p m="t-0 b-2">商品id: {{ props.row.id }}</p>
              <p m="t-0 b-2" style="margin-left: 30%;">商品名: {{ props.row.name }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" />
        <el-table-column label="商品分类" prop="category" />
        <el-table-column label="商品价格" prop="price" />
        <el-table-column label="商品图片" prop="imgUrl">
          <template #default="scope">
            <img :src="serverUrl + scope.row.imgUrl" alt="商品图片" style="width: 50px; height: 50px; object-fit: cover;">
          </template>
        </el-table-column>
        <el-table-column label="商品描述" prop="goodsDesc" />

        <el-table-column label="操作" width="180">
          <template #default="scoped">
            <el-button size="default" plain @click="handleEdit(scoped.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="handleDelete(scoped.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="formData.currentPage" v-model:page-size="formData.pageSize"
          :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="editDialogVisible" title="编辑商品" width="800px">
      <el-form :model="editForm" ref="editFormRef" :label-width="formLabelWidth">
        <el-form-item label="商品id">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="editForm.category" :options="options" placeholder="请选择商品分类">
            <el-option v-for="item in options" :key="item.value" :label="item.cateName" :value="item.cateName" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input-number v-model="editForm.price" :min="0" />
        </el-form-item>
        <el-form-item label="商品图片">
            <el-upload
                action="/api/goods/goods_img_upload"
                :on-success="handleEditUploadSuccess"
                :before-upload="beforeEditUpload"
                :show-file-list="false"
            >
            <img v-if="editForm.imgUrl" :src="'/api/upload/imgs/goods_img/'+editForm.imgUrl" style="width: 150px; height: 150px;object-fit: cover;"/>
                <div v-else class="el-upload__text">
                    <el-icon><Plus /></el-icon>
                    <div class="el-upload__hint">点击上传商品图片</div>
                </div>
            </el-upload>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="editForm.goodsDesc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { goodsList, goodsDel,cateEdit,getCate,goodsEdit} from '../api/goods'
import { serverUrl } from '../utils/common'
import { ElMessage } from 'element-plus'

const size = ref('medium')
const parentBorder = ref(false)
const tableData = ref([])
const preserveExpanded = ref(false)

const total = ref(0)
const formData = reactive({
  currentPage: 1,
  pageSize: 5
})
const background = ref(true)
const disabled = ref(false)

const editDialogVisible = ref(false)
const editForm = reactive({
  name: '',
  category: '',
  price: '',
  imgUrl: '',
  goodsDesc: '',
  id: ''
})
const editFormRef = ref()



const options = ref([])
// 获取商品分类选项
const fetchCategories = async () => {
  try {
    await getCate().then(res => {
      console.log(res);
      options.value = res.categories;
      console.log(options.value);
    })
  }
  catch (error) {
    console.error('获取分类失败:', error);
  }
}
fetchCategories()

const getListAccount = async () => {
  const res = await goodsList(formData)
  console.log(res);
  tableData.value = res.data;
  total.value = res.total;

}
getListAccount()



const handleSizeChange = (val) => {
  getListAccount()
}
const handleCurrentChange = (val) => {
  getListAccount()
}

const handleEdit = (row) => {
  Object.assign(editForm, row)
  editDialogVisible.value = true
}


const handleEditUploadSuccess = (res) => {
    console.log('编辑时图片上传成功，返回数据:', res);
    if (res.code === 0) { // 假设返回码 0 表示成功
        editForm.imgUrl = res.imgUrl.replace('/upload/imgs/goods_img/', '');
        console.log('编辑时 imgUrl 被更新为:', editForm.imgUrl);
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error('图片上传失败');
    }
}

//  编辑时上传前的校验
const beforeEditUpload = (file) => {
    const isImage = /^image\//.test(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    console.log('编辑时 beforeUpload 函数执行，文件:', file);

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        console.log('文件类型不符合要求');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        console.log('文件大小超过限制');
    }
    return isImage && isLt2M;
}


const submitEdit = async () => {
    if (!editForm.imgUrl) {
        ElMessage.error('请上传商品图片');
        return;
    }
    console.log(editForm);
    try {
        const { code, msg } = await goodsEdit(editForm); 
        if (code === 0) {
            ElMessage.success(msg);
            if (editFormRef.value) { 
                editFormRef.value.resetFields();
            }
            editDialogVisible.value = false; 
            getListAccount(); 
        } else {
            ElMessage.error(msg);
        }
    } catch (error) {
        // 打印详细错误信息
        console.error('提交表单时出错，详细信息:', error); 
        ElMessage.error('提交表单时出错');
    }
};


const handleDelete = async (id) => {
  const res = await goodsDel({ id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getListAccount()
  }
  else {
    ElMessage({
      type: 'error',
      message: '删除失败'
    })
  }
}
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  /* display: flex; */
  background-color: #fff;
  border-radius: 6px;

}

.top {
  width: 100%;
  height: 6%;
  font-size: 18px;
  /* font-weight: bold; */
  border-bottom: 1px solid #888787;
}

.top h1 {
  margin-left: 20px;
  line-height: 40px;
}

.demo-pagination-block {
  margin-top: 20px;
  padding: 0 20px;
}

.content {
  padding: 20px;
}

.launched {
  padding: 10px;
  display: flex;
}
</style>